package com.c.ctgproject.ui.collect

import android.app.Activity
import android.content.Intent
import android.view.View
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityCarSearchBinding
import com.c.ctgproject.utils.*
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.common.Constant
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import java.lang.Exception

/**
 *作者:LiBW
 *创建日期: 2021/10/7
 *描述: 车辆查询 页面
 */
class CarSearchActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityCarSearchBinding.inflate(layoutInflater) }
    //0 搜索车辆信息 1 搜索电池信息 2散件查询
    private val searchType by lazy { intent.getIntExtra("searchType",0) }
    override fun getLayout() = mBinding.root

    //二维码回调
    private val requestCodeScan = 10001
    override fun event() {

    }

    override fun click() {
        when(searchType){
            1->{
               mBinding.mScanQrBTN.visibility= View.INVISIBLE
                mBinding.mSearchET.hint="请输入电池自编码、车辆自编码、入库单号"
            }
            2->{
                mBinding.mScanQrBTN.visibility= View.INVISIBLE
                mBinding.mSearchET.hint="请输入零件自编码，零件名称，车辆编码，入库编码"
            }
        }
        //扫码
        mBinding.mScanQrBTN.setOnClickListener {
            startActivityForResult(Intent(this, CaptureActivity::class.java), requestCodeScan)
        }
        mBinding.mSearchIV.setOnClickListener {
            val search = mBinding.mSearchET.text.handlerNull()
            if (search.isEmpty()) {
                showToast("请输入要搜索的内容")
            } else {
                when(searchType){
                    0->startActivity<CarSearchListActivity>(MyConstants.SEARCH to search)
                    1->startActivity<SearchBatteryActivity>(MyConstants.SEARCH to search)
                    2->startActivity<SearchPartActivity>(MyConstants.SEARCH to search)
                }

            }
        }


    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            //二维码回调
            if (requestCode == requestCodeScan && data != null) {
                val content: String? = data.getStringExtra(Constant.CODED_CONTENT)
                MyLog.d("二维码扫描结果:$content")
                content?.let {
                    try {
                        val json = JSONObject(content)
                        val carId = json.getInt("id")
                        startActivity<SearchCarInfoActivity>(MyConstants.CAR_ID to carId)
                    } catch (e: Exception) {
                        showToast("二维码数据异常")
                    }
                }
            }
        }
    }
}